package cn.passlink.bletoothchat.mActivity;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.sqlite.SQLiteDatabase;
import android.location.Location;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import java.util.HashMap;
import java.util.List;

import cn.passlink.bletoothchat.R;
import cn.passlink.bletoothchat.SqlTables.MyDatabaseHelper;
import cn.passlink.bletoothchat.Tools.Location.GPSHelper;
import cn.passlink.bletoothchat.Tools.Location.WifiLocationHelper;
import cn.passlink.bletoothchat.mFragment.FriendsScrollingFragment;
import cn.passlink.bletoothchat.mFragment.GroupsScrollingFragment;
@SuppressLint("MissingPermission")
public class RelationshipActivity extends AppCompatActivity{
    private SQLiteDatabase database;
    private MyDatabaseHelper databaseHelper;
    private GPSHelper gpsHelper;
    private WifiLocationHelper wifiLocationHelper;
    private WifiManager wifiManager;
    private Context mContext;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_relationship);
        mContext=this;
        // 初始化视图
        ImageView  backButton = findViewById(R.id.relationship_back_button);
        ImageView addFriendsButton = findViewById(R.id.add_friends_groups_button);
        ImageView createGroupButton = findViewById(R.id.create_groups_button);
        Button friendsButton = findViewById(R.id.friends_button);
        Button groupsButton = findViewById(R.id.groups_button);

        // 设置点击事件
        backButton.setOnClickListener(v -> goToTargetActivity(RegisterActivity.class, "key", "value"));

        addFriendsButton.setOnClickListener(v -> goToTargetActivity(AddFriendsActivity.class, "key", "value"));

        createGroupButton.setOnClickListener(v -> goToTargetActivity(CreateGroupActivity.class, "key", "value"));

        friendsButton.setOnClickListener(v -> replaceFragment(new FriendsScrollingFragment()));

        groupsButton.setOnClickListener(v -> replaceFragment(new GroupsScrollingFragment()));

        // 显示默认的 Fragment
        replaceFragment(new FriendsScrollingFragment());
        // 创建 GPSHelper 实例
        gpsHelper = new GPSHelper(this);

        // 请求位置更新
        gpsHelper.requestLocationUpdates(locationListener);

        wifiLocationHelper = new WifiLocationHelper(this);
        wifiManager = (WifiManager) this.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        //开启数据库
        databaseHelper = new MyDatabaseHelper(this,2);
        database=databaseHelper.getWritableDatabase();

    }


//GPS----------------------------------------------------------------------------------
    GPSHelper.CustomLocationListener locationListener = new GPSHelper.CustomLocationListener() {
        @Override
        public void onLocationChanged(Location location) {
            // 处理位置变化事件
            double latitude = location.getLatitude();
            double longitude = location.getLongitude();
            //写入数据库
            //更新GPS位置写入个人信息
            if(latitude!=0 && longitude!=0){
                ContentValues values = new ContentValues();
                values.put("position", longitude+"--"+latitude);
                String whereClause = "id=?";
                String[] whereArgs = {"1"};
                database.update("user", values, whereClause, whereArgs);
            }
            Log.d("GPS",longitude+"-"+latitude);
        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
            // 当位置状态发生变化时触发此方法
            // 处理位置状态变化事件
        }

        @Override
        public void onProviderEnabled(String provider) {
            // 当定位提供者启用时触发此方法
            // 处理定位提供者启用事件
        }

        @Override
        public void onProviderDisabled(String provider) {
            // 当定位提供者禁用时触发此方法
            // 处理定位提供者禁用事件
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(database!=null){
            database.close();
        }
        // 注销位置监听
        wifiLocationHelper.stopScan();
        gpsHelper.removeLocationUpdates();
  //注销
        unregisterReceiver(BleState);
    }


//WIFI----------------------------------------------------------------------------------

    @Override
    protected void onResume() {
        super.onResume();
        //注册
        wifiLocationHelper = new WifiLocationHelper(mContext);
        wifiLocationHelper.startScan();
        wifiManager = (WifiManager) mContext.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        registerReceiver(wifiScanReceiver, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
        // 在Activity或Fragment的onResume方法中注册广播接收器
        IntentFilter filter = new IntentFilter("BleStateBroadcast");
        registerReceiver(BleState, filter);

    }

    @Override
    protected void onPause() {
        super.onPause();
        //注销广播接收器
        unregisterReceiver(wifiScanReceiver);
    }

    //wifi广播接收扫描结果
    private final BroadcastReceiver wifiScanReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (WifiManager.SCAN_RESULTS_AVAILABLE_ACTION.equals(intent.getAction())) {
                List<ScanResult> scanResults = wifiManager.getScanResults();
                HashMap<String, String> locationMap = new HashMap<>();
                //没在学校无法采集，随便编的几个意思一下
                locationMap.put("10:3A:DD:FA:4C:09", "立人楼");
                locationMap.put("5C:33:8E:21:E7:BF", "品学楼");
                locationMap.put("AC:F1:DF:9B:88:72", "八角书斋");
                locationMap.put("1A:7B:2C:EF:5D:94", "信息楼");
                locationMap.put("E2:88:70:92:A4:C5", "信通科研楼");
                locationMap.put("73:CF:4B:67:FA:0E", "商业街");
                for (ScanResult scanResult : scanResults) {
                    String bssid = scanResult.BSSID;
                    if (locationMap.containsKey(bssid)) {
                        String location = locationMap.get(bssid);
                        // 这里根据位置范围进行相应的处理逻辑
                        ContentValues values = new ContentValues();
                        values.put("area",location);
                        String whereClause = "id=?";
                        String[] whereArgs = new String[]{"1"};
                        database.update("user", values, whereClause, whereArgs);

                    }
                    else {
                        ContentValues values = new ContentValues();
                        values.put("area", "学之苑");
                        String whereClause = "id=?";
                        String[] whereArgs = new String[]{"1"};
                        database.update("user", values, whereClause, whereArgs);


                    }
                }

            }
        }
    };
    //跳转
    public void goToTargetActivity(Class myclass, String key, String value) {
        Intent intent = new Intent(this, myclass);
        intent.putExtra(key, value);
        startActivity(intent);
    }

    //切换页面
    private void replaceFragment(Fragment fragment) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.replace(R.id.Relation_Fragment, fragment);
        fragmentTransaction.commit();
    }



    // 创建广播接收器
    private BroadcastReceiver BleState = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            // 处理接收到的广播消息
            if (intent.getAction().equals("BleStateBroadcast")) {
                String message = intent.getStringExtra("message");
                switch (message){
                    case "100":
                        Toast.makeText(context, "蓝牙连接中。。。" + message, Toast.LENGTH_SHORT).show();break;
                    case "200":
                        Toast.makeText(context, "蓝牙连接SERVER成功可以尝试聊天了！！！" + message, Toast.LENGTH_SHORT).show();break;
                    case "500":
                        Toast.makeText(context, "断开中 " + message, Toast.LENGTH_SHORT).show();break;
                    case "400":
                        Toast.makeText(context, "蓝牙已断开！！！！ " + message, Toast.LENGTH_SHORT).show();break;
                    case "1000":
                        Toast.makeText(context, "蓝牙连接CLIENT成功可以尝试聊天了！！！！ " + message, Toast.LENGTH_SHORT).show();break;

                }


            }
        }
    };


}